/**
 * 
 */
package com.estock.crawler.writer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.csvreader.CsvWriter;
import com.estock.common.util.FileUtil;
import com.estock.crawler.utils.ESCrawlerUtil;

/**
 * @author richard
 *
 */
public class JqkaStockWorthCsvWriter implements AbstractJqkaStockCsvWriter {
	private static final Logger logger = LoggerFactory.getLogger(JqkaStockWorthCsvWriter.class);
	
	private static CsvWriter cw;
	private static File csv;
	
	private Document doc;
	private String stockcode;
	
	static {
		csv = new File(ESCrawlerUtil.get10jqkaCsvDir() + "Jqka_Worth_ForecastAgg.csv");
		FileUtil.createIfNotExists(csv);
		
		try {
			OutputStream os = new FileOutputStream(csv);
			byte[] bom ={(byte) 0xEF,(byte) 0xBB,(byte) 0xBF};
			os.write(bom); // does not use cw.write because that appends another character ','
			
			cw = new CsvWriter(os, ',', Charset.forName("UTF-8"));
			cw.write("Code");
			cw.write("MainBizDesc");
			cw.write("Industry");
			cw.write("Concepts");
			cw.write("DynamicPE");
			cw.write("EPS");
			cw.write("ROE");
			cw.write("StockGroup");
			cw.write("StaticPE");
			cw.write("Revenue");
			cw.write("NAPS");
			cw.write("TotalShares");
			cw.write("PB");
			cw.write("NetProfit");
			cw.write("CFPS");
			cw.write("TradableShares");
			cw.write("LatestUnlocks");
			cw.endRecord();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			cw.close();
		}
	}
	
	public JqkaStockWorthCsvWriter(Document doc, String stockcode) {
		this.doc = doc;
		this.stockcode = stockcode;
	}
	
	@Override
	public void write() {
		Elements compSummary = doc.select("#profile .bd table td");
		if (compSummary == null || compSummary.isEmpty()) {
			logger.error("No valid data found!");
			System.out.println("No valid data found!");
			return;
		}
		
		try {
			cw = new CsvWriter(new FileWriter(csv, true), ',');
			cw.write(stockcode);
			cw.write(compSummary.get(0).select(".skipto").attr("title")); // 主营业务
			cw.write(compSummary.get(1).select(".f14").text());         // 所属行业
			cw.write(compSummary.get(2).select(".newconcept").html().split("<a")[0]); // 涉及概念
			cw.write(doc.select("#dtsyl").text());						// 市盈率(动态)
			cw.write(compSummary.get(4).select("span").get(1).text());  // 每股收益
			cw.write(compSummary.get(5).select("span").get(1).text());  // 净资产收益率
			cw.write(compSummary.get(6).select("span").get(1).text());  // 分类
			cw.write(doc.select("#jtsyl").text());  					// 市盈率(静态)
			cw.write(compSummary.get(8).select("span").get(1).text());  // 营业收入
			cw.write(compSummary.get(9).select("span").get(1).text());  // 每股净资产
			cw.write(compSummary.get(10).select("span").get(1).text()); // 总股本
			cw.write(doc.select("#sjl").text());   						// 市净率
			cw.write(compSummary.get(12).select("span").get(1).text()); // 净利润
			cw.write(compSummary.get(13).select("span").get(1).text()); // 每股现金流
			cw.write(compSummary.get(14).select("span").get(1).text()); // 流通A股
			cw.write(compSummary.get(17).select("span").get(1).text()); // 最新解禁
			cw.endRecord();
			cw.close();
		} catch (IOException e) {
			logger.error("Error in writing csv file for stockcode= " + stockcode);
		}
		
		System.out.println("Successfully write data to " + csv.getAbsolutePath());
		
	}
	
	
	////////////// Testing method
	public static void main(String[] args) {
		Document doc = Jsoup.parse(
				FileUtil.readString(ESCrawlerUtil.get10jqkaRawDataDir() + "basic.10jqka.com.cn/000413/worth.html", "GBK"));
		new JqkaStockWorthCsvWriter(doc, "000413").write();
	}

}
